<template>
  <!-- ceshi1111111111 -->
  <div class="viewContain">
    <div v-loading.fullscreen.lock="allLoading" class="all">
      <div class="left">
        <div class="left-table">
          <el-form :model="listQuery" size="small" label-width="80px">
            <el-row>
              <input type="hidden" value="listQuery.userId">
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 8 }" :xl="{ span: 8 }">
                <el-form-item label="设备编号" prop="equipmentNo">
                  <el-input
                    v-model="listQuery.equipmentNo"
                    placeholder="请输入设备设备编号"
                    clearable
                    @keyup.enter.native="handleSearch"
                  />
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 8 }" :xl="{ span: 8 }">
                <el-form-item label="设备状态" prop="state">
                  <el-select v-model="listQuery.state" clearable placeholder="设备状态">
                    <el-option v-for="item in options" :key="item.value" :label="item.label" :value="item.value" />
                  </el-select>
                </el-form-item>
              </el-col>
              <el-col :xs="{ span: 24 }" :sm="{ span: 12 }" :md="{ span: 8 }" :xl="{ span: 8 }">
                <el-form-item label-width="20px" prop="state">
                  <el-button size="mini" type="primary" @click="handleSearch">查询</el-button>
                  <el-button size="mini" type="primary" plain @click="resetInput">重置</el-button>
                </el-form-item>
              </el-col>
            </el-row>
          </el-form>
          <!--数据列表-->
          <el-table
            ref="multipleTable"
            v-loading="loading"
            fit
            :data="tableData"
            :height="height"
            border
            size="mini"
            @selection-change="handleSelectionChange"
          >
            <el-table-column type="selection" width="55" align="center" />
            <el-table-column label="序号" align="center">
              <template slot-scope="scope">
                <span>{{ (listQuery.pageNo - 1) * listQuery.pageSize + scope.$index + 1 }}</span>
              </template>
            </el-table-column>
            <el-table-column prop="deviceIp" label="设备ip" align="center" width="115" />
            <el-table-column prop="deviceMac" label="设备mac" align="center" width="115" />
            <el-table-column prop="deviceName" label="设备名称" align="center" width="150" />
            <el-table-column prop="equipmentNo" label="设备id" align="center" width="150" />
            <el-table-column prop="partkind" label="设备类型" align="center" />
            <el-table-column prop="state" label="状态" align="center">
              <template slot-scope="scope">
                <span v-if="scope.row.state == '可用' ">可用</span>
                <span v-if="scope.row.state == '维护' ">维护</span>
                <span v-if="scope.row.state == '停用' ">停用</span>
              </template>
            </el-table-column>
          </el-table>
          <pagination
            :total-count="totalCount"
            :page.sync="listQuery.pageNo"
            :limit.sync="listQuery.pageSize"
            @pagination="getList"
          />
        </div>
        <div class="left-point" :style="{height: height2}">
          <div class="center-div" @click="mutiSel()">
            <i class="el-icon-caret-right" />
          </div>
        </div>
      </div>
      <div class="right">
        <el-form size="small">
          <el-row>
            <el-col>
              <el-form-item label-width="20px" prop="state" align="right">
                <el-button size="mini" type="primary" @click="handleBind">绑定</el-button>
                <el-button type="primary" plain size="mini" @click="handleBack">返回</el-button>
              </el-form-item>
            </el-col>
          </el-row>
        </el-form>
        <!--数据列表-->
        <el-table
          ref="table"
          fit
          :data="tableDataBind"
          :height="height"
          border
          size="mini"
        >
          <el-table-column label="序号" align="center" type="index" />
          <el-table-column prop="deviceIp" label="设备ip" align="center" width="115" />
          <el-table-column prop="deviceMac" label="设备mac" align="center" width="115" />
          <el-table-column prop="deviceName" label="设备名称" align="center" width="150" />
          <el-table-column prop="equipmentNo" label="设备id" align="center" width="150" />
          <el-table-column prop="partkind" label="设备类型" align="center" />
          <el-table-column prop="state" label="状态" align="center">
            <template slot-scope="scope">
              <span v-if="scope.row.state == '可用' ">可用</span>
              <span v-if="scope.row.state == '维护' ">维护</span>
              <span v-if="scope.row.state == '停用' ">停用</span>
            </template>
          </el-table-column>
          <el-table-column align="center" label="操作" width="80" fixed="right">
            <template slot-scope="scope">
              <el-button class="text-button el-button--danger" size="mini" @click="handleDelete(scope.$index)">删除</el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>
  </div>
</template>
<script>
import { validPhone } from '@u/validate'
import { commonMixin } from '@v/mixin/commonMixin.js'
import ComApiUrl from '@a/comomApi.js'
import pagination from '@/components/pagination/index.vue'
// eslint-disable-next-line no-unused-vars
import { bindDevice } from '@a/software/software.js'

export default {
  components: { pagination },
  mixins: [commonMixin],
  data() {
    const validatePhone = (rules, value, callback) => {
      if (!validPhone(value)) {
        callback(new Error('手机号格式输入有误!'))
      } else {
        callback()
      }
    }

    const validateFinace = (rules, value, callback) => {
      console.log('isfinance' + parseInt(value))
      if (parseInt(value) === 1) {
        console.log(this.formData.tenantNo + ', zdCode:' + this.formData.terminalNo)
        if (this.formData.tenantNo === undefined || this.formData.terminalNo === undefined || this.formData.tenantNo === '' || this.formData.terminalNo === '') {
          callback(new Error('选择金融功能后需要填写商户号与终端号!'))
        } else {
          callback()
        }
      } else {
        callback()
      }
    }

    return {
      comApiUrlList: new ComApiUrl('/device/api/v2/deviceInfo/list'),
      comApiUrlAdd: new ComApiUrl('/device/api/v2/deviceInfo/register'),
      comApiUrlUpdate: new ComApiUrl('/device/api/v2/deviceInfo/update'),
      height: window.innerHeight - 270,
      height2: window.innerHeight - 200 + 'px',
      loading: false,
      allLoading: false,
      dialogVisble: false,
      dialogFormVisible_detail: false,
      currentPage: 1,
      financeFlag: true,
      partkinds: [],
      formData: {},
      deviceDialog: '设备详情',
      oId: this.$route.query.id,
      listQuery: {
        pageSize: 10,
        pageNum: 1,
        userId: '',
        state: '',
        areaCode: '',
        equipmentNo: '',
        orgId: '0',
        apkId: this.$route.query.id,
        bindState: 'W'
      },
      detailInfo: {
        areaName: '',
        createTime: '',
        deviceIp: '',
        deviceMac: '',
        deviceName: '',
        equipmentNo: '',
        id: '',
        orgId: '',
        orgName: '',
        owner: '',
        ownerLink: '',
        partkind: '',
        state: '',
        updateTime: '',
        isFinance: 1,
        tenantNo: '',
        terminalNo: '',
        imei: ''
      },
      tableData: [],
      tableDataBind: [],
      tableDataBak: [],
      options: [
        {
          value: 'Y',
          label: '可用'
        },
        {
          value: 'W',
          label: '维护'
        },
        {
          value: 'T',
          label: '停用'
        }
      ],
      orgs: [],
      casProps: {
        checkStrictly: true, // 是否严格的遵守父子节点不互相关联
        emitPath: false, // 在选中节点改变时，是否返回由该节点所在的各级菜单的值所组成的数组，若设置 false，则只返回该节点的值
        value: 'orgId', // 指定选项的值为选项对象的某个属性值
        label: 'name' // 指定选项标签为选项对象的某个属性值
      },
      value: '',
      rules: {
        deviceName: [
          { required: true, message: '设备名不能为空', trigger: 'blur' }
        ],
        equipmentNo: [
          { required: true, message: '设备编号不能为空', trigger: 'blur' }
        ],
        orgId: [
          { required: true, message: '网点id不能为空', trigger: 'blur' }
        ],
        owner: [
          { required: true, message: '持有人不能为空', trigger: 'blur' }
        ],
        ownerLink: [
          { required: true, message: '持有人联系方式不能为空', trigger: 'blur' },
          { validator: validatePhone, trigger: 'blur' }
        ],
        partkind: [
          { required: true, message: '设备类型不能为空', trigger: 'blur' }
        ],
        state: [
          { required: true, message: '请选择设备状态', trigger: 'blur' }
        ],
        isFinance: [
          { validator: validateFinace, trigger: 'blur' }
        ]
      },
      userId: ''
    }
  },
  watch: {
    'formData.isFinance'(val) {
      if (parseInt(val) === 1) {
        this.financeFlag = false
      }
      if (parseInt(val) === 0) {
        this.financeFlag = true
      }
    }
  },
  mounted() {
    const userInfo = JSON.parse(localStorage.getItem('userInfo'))
    this.userId = userInfo.userId
    this.getList()
  },
  methods: {
    handleBack() {
      this.$router.go(-1)
    },

    handleDelete(index) {
      this.tableDataBind.splice(index, 1)
    },

    mutiSel() {
      const lengthBak = this.tableDataBak.length
      const length = this.tableDataBind.length
      const list = [].concat(this.tableDataBind)
      if (lengthBak === 0) {
        this.$message({
          type: 'warning',
          message: '请至少选择一条数据'
        })
      } else if (length === 0) {
        this.tableDataBind = [].concat(this.tableDataBak)
        this.$refs.multipleTable.clearSelection();
      } else {
        this.tableDataBak.forEach(item => {
          this.tableDataBind.push(item)
          list.forEach(ele => {
            if (ele.id === item.id) {
              this.tableDataBind.pop(item)
            }
          })
        })
        this.$refs.multipleTable.clearSelection();
      }
    },
    toggleSelection(rows) {
      if (rows) {
        rows.forEach(row => {
          this.$refs.multipleTable.toggleRowSelection(row);
        });
      } else {
        this.$refs.multipleTable.clearSelection();
      }
    },
    handleSelectionChange(val) {
      this.tableDataBak = val
    },

    // 重置查询输入框中的值
    resetInput() {
      this.listQuery.equipmentNo = ''
      this.listQuery.state = ''
      this.getList()
    },

    // 查询,显示所有设备信息
    getList() {
      this.listQuery.userId = this.userId
      this.getInfo()
    },

    // 确认绑定
    handleBind() {
      console.log('确认绑定');
      if (this.tableDataBind.length === 0) {
        this.$message({
          type: 'warning',
          message: '请至少选择一条数据'
        })
      } else {
        this.allLoading = true
        const equipmentId = this.tableDataBind.map(item => item.equipmentNo).join(',')
        const params = { id: this.oId, equipmentId }
        bindDevice(params).then(res => {
          this.allLoading = false
          if (res.code === 0) {
            this.getList()
            this.tableDataBind = []
            this.$message({
              type: 'success',
              message: res.msg
            })
          } else {
            this.$message({
              type: 'error',
              message: res.msg
            })
          }
        }).catch(err => console.log(err))
      }
    }
  }
}
</script>
<style lang="scss" scoped>
.all {
  width: 100%;
  .left {
    width: 56%;
    // border: 1px solid #ccc;
    float: left;
    .left-table {
      width: 86%;
      float: left;
    }
  }
  .left-point {
    width: 10%;
    margin: 0 2%;
    float: left;
    display: flex;
    .center-div, i {
      width: 40px;
      height: 40px;
      font-size: 22px;
      line-height: 40px;
      text-align: center;
      color: #fff;
      background: #0079d0;
      border-radius: 20px;
      margin: auto;
    }
  }
  .right {
    width: 42%;
    // border: 1px solid #ccc;
    float: left;
  }
}
</style>
